import { Sequelize } from 'sequelize'
import dotenv from 'dotenv'

// 加载环境变量
dotenv.config()

// 数据库配置
const dbConfig = {
  host: process.env.DB_HOST || 'localhost',
  port: process.env.DB_PORT || 3306,
  database: process.env.DB_NAME || 'blog',
  username: process.env.DB_USER || 'root',
  password: process.env.DB_PASSWORD || '123456',
  dialect: 'mysql',
  logging: process.env.NODE_ENV === 'development' ? console.log : false,
  timezone: '+08:00',
  freezeTableName: true,
  pool: {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000
  },
  define: {
    timestamps: true,
    underscored: true
  }
}

// 创建 Sequelize 实例
const sequelize = new Sequelize(
  dbConfig.database,
  dbConfig.username,
  dbConfig.password,
  {
    host: dbConfig.host,
    port: dbConfig.port,
    dialect: dbConfig.dialect,
    logging: dbConfig.logging,
    timezone: dbConfig.timezone,
    freezeTableName: dbConfig.freezeTableName,
    pool: dbConfig.pool,
    define: dbConfig.define
  }
)

// 测试数据库连接
export const testConnection = async () => {
  try {
    await sequelize.authenticate()
    console.log('✅ 数据库连接成功')
    return true
  } catch (error) {
    console.error('❌ 数据库连接失败:', error.message)
    return false
  }
}

// 同步数据库模型
export const syncDatabase = async (force = false) => {
  try {
    if (force) {
      await sequelize.sync({ force: true })
      console.log('✅ 数据库表已重新创建')
    } else {
      await sequelize.sync({ alter: true })
      console.log('✅ 数据库表已同步')
    }
    return true
  } catch (error) {
    console.error('❌ 数据库同步失败:', error.message)
    return false
  }
}

export default sequelize
